package com.mvc.finance.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mvc.finance.model.Currency;
import com.mvc.finance.service.CurrencyManager;
import com.mvc.framework.model.Dictionary;
import com.mvc.framework.service.DictionaryFacade;
import com.mvc.framework.service.PageManager;
import com.mvc.framework.web.BaseController;

@Controller
@RequestMapping("currency")
public class CurrencyController extends BaseController<Currency> {
	@Autowired
	private CurrencyManager	 currencyManager;

	@Autowired
	private DictionaryFacade	dictionaryFacade;

	protected String handleEdit(HttpServletRequest request, HttpServletResponse response, Integer id) throws Exception {
		List<Currency> currencies = currencyManager.getAll();
		List<Dictionary> dictionaries = dictionaryFacade.getDictionariesByDictionaryId(1006);
		for (Dictionary dictionary : dictionaries) {
			for (Currency currency : currencies) {
				if (dictionary.getValue().equals(currency.getId())) {
					dictionary.setReserver1(String.valueOf(currency.getRate()));
					break;
				}
			}
		}
		request.setAttribute("dictionaries", dictionaries);
		return getFileBasePath() + "editCurrency";
	}

	@RequestMapping("saveAll")
	public String saveAll(HttpServletRequest request) {
		String[] ids = request.getParameterValues("id");
		String[] rates = request.getParameterValues("rate");
		for (int i = 0; i < ids.length; i++) {
			Currency currency = new Currency();
			currency.setId(Integer.parseInt(ids[i]));
			currency.setRate(Double.parseDouble(rates[i]));
			currencyManager.save(currency);
		}
		return "redirect:create";
	}

	@Override
	public PageManager getEntityManager() {
		return currencyManager;
	}

	@Override
	public String getFileBasePath() {
		return "finance/";
	}
}
